﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Enterprise.Infrastructure;
using Enterprise.Model.Module;
using Enterprise.Data.Module;
using Enterprise.Service.User;
namespace Enterprise.Service.Module
{
    /// <summary>
    /// 系统模块业务服务
    /// </summary>
    public class ModuleService
    {
        /// <summary>
        ///  系统模块缓存标记
        /// </summary>
        private static string cacheKey = "Enterprise-Module";

        /// <summary>
        /// 系统用户菜单缓存标记
        /// </summary>
        private static string cacheKeyMenu = "Enterprise-Menu";

        /// <summary>
        /// 系统模块列表 返回所有模块记录
        /// </summary>
        /// <returns></returns>
        public List<ModuleEntity> ModuleList()
        {
            if (CacheHelper.Contains(cacheKey))
            {
                return (List<ModuleEntity>)CacheHelper.GetCache(cacheKey);
            }
            else
            {
                ModuleData data = new ModuleData();
                List<ModuleEntity> list = data.ModuleList().OrderBy(p => p.MORDERBY).ToList();
                CacheHelper.Add(cacheKey, list);
                return list;
            }
        }

        /// <summary>
        /// 系统模块记录 返回单个模块记录
        /// </summary>
        /// <param name="mId"></param>
        /// <returns></returns>
        public ModuleEntity ModuleDisp(int mId)
        {
            return ModuleList().Where(p => p.MODULEID == mId).FirstOrDefault();
        }

        /// <summary>
        /// 系统模块上移一位
        /// </summary>
        /// <param name="Id"></param>
        public void ModuleMoveUpService(int Id)
        {
            var entity = ModuleDisp(Id);
            if (entity != null)
            {
                var upentity = ModuleList().Where(p => p.MPARENTID == entity.MPARENTID && p.MORDERBY < entity.MORDERBY).OrderByDescending(p=>p.MORDERBY).FirstOrDefault();
                if (upentity != null)
                {
                    string upcmd = "Update SYS_MODULE set MORDERBY=" + entity.MORDERBY + "where MODULEID=" + upentity.MODULEID;
                    ModuleExecuteBySql(upcmd, 0);
                    string cmd = "Update SYS_MODULE set MORDERBY=" + upentity.MORDERBY + " where MODULEID=" + entity.MODULEID;
                    ModuleExecuteBySql(cmd, 0);
                    ClearCache();
                }
            }
        }

        /// <summary>
        /// 系统模块下移一位
        /// </summary>
        /// <param name="Id"></param>
        public void ModuleMoveDownService(int Id)
        {
            var entity = ModuleDisp(Id);
            if (entity != null)
            {
                var downentity = ModuleList().Where(p => p.MPARENTID == entity.MPARENTID && p.MORDERBY > entity.MORDERBY).OrderBy(p => p.MORDERBY).FirstOrDefault();
                if (downentity != null)
                {
                    string upcmd = "Update SYS_MODULE set MORDERBY=" + (entity.MORDERBY) + "where MODULEID=" + downentity.MODULEID;
                    ModuleExecuteBySql(upcmd, 0);
                    string cmd = "Update SYS_MODULE set MORDERBY=" + (downentity.MORDERBY) + " where MODULEID=" + entity.MODULEID;
                    ModuleExecuteBySql(cmd, 0);
                    ClearCache();
                }
            }
        }

        /// <summary>
        /// 获取功能菜单模块最大排序值
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public int GetMaxModuleOrderBy(int ParentId)
        {
            var q = ModuleList().Where(p => p.MPARENTID == ParentId).OrderByDescending(p => p.MORDERBY).FirstOrDefault();
            if (q != null)
            {
                return q.MORDERBY;
            }
            return 0;
        }


        /// <summary>
        /// 模块操作 添加、修改、删除
        /// </summary>
        /// <param name="entity">用户实体</param>
        public void ModuleExecute(ModuleEntity entity)
        {
            string cmd = string.Empty;
            switch (entity.DB_Option_Action)
            {
                case "Insert":
                    cmd = "Insert into SYS_MODULE(PBGROUP,MCODE,MNAME,MPARENTID,MROOTID,MIMAGE,MSINGLE,MTARGET,MURL,MDELETE,MORDERBY) values('" + entity.PBGROUP + "','" + entity.MCODE + "','" + entity.MNAME + "'," + entity.MPARENTID + "," + entity.MROOTID + ",'" + entity.MIMAGE + "',"+entity.MSINGLE+",'" + entity.MTARGET + "','" + entity.MURL + "','" + entity.MDELETE + "'," + entity.MORDERBY + ")";
                    break;
                case "Update":
                    cmd = "Update SYS_MODULE set PBGROUP='" + entity.PBGROUP + "' , MCODE='" + entity.MCODE + "' , MNAME='" + entity.MNAME + "' , MPARENTID=" + entity.MPARENTID + " , MROOTID=" + entity.MROOTID + " , MIMAGE='" + entity.MIMAGE + "',MSINGLE=" + entity.MSINGLE + " , MTARGET='" + entity.MTARGET + "' , MURL='" + entity.MURL + "' , MDELETE='" + entity.MDELETE + "' , MORDERBY=" + entity.MORDERBY + " where MODULEID=" + entity.MODULEID;
                    break;
                case "Delete":
                    cmd = "Delete from SYS_MODULE where MODULEID=" + entity.MODULEID;
                    break;
                case "UpdatemDelete":
                    cmd = "Update SYS_MODULE set MDELETE='" + entity.MDELETE + "' where MODULEID=" + entity.MODULEID;
                    break;
            }
            if (!string.IsNullOrEmpty(cmd))
            {
                ModuleExecuteBySql(cmd, 1);
            }
        }

        /// <summary>
        /// 清楚缓存
        /// </summary>
        private void ClearCache()
        {
            CacheHelper.RemoveCache(cacheKey);
            CacheHelper.RemoveCache(cacheKeyMenu);
        }

        /// <summary>
        /// 模块操作
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="typeId"></param>
        public void ModuleExecuteBySql(string cmd,int typeId)
        {
            ModuleData data = new ModuleData();
            data.ModuleExecute(cmd);
            if (typeId == 1)
            {
                CacheHelper.RemoveCache(cacheKey);
            }
            
        }

        #region "获取模块名称"
        /// <summary>
        /// 获取模块名称
        /// </summary>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public static string GetModuleName(int moduleId)
        {
            ModuleService mService = new ModuleService();
            var query = mService.ModuleDisp(moduleId);
            if (query != null)
            {
                return query.MNAME;
            }
            return "";
        }


        #endregion

        #region "EasyUI-According折叠菜单Html"

        /// <summary>
        /// 获得折叠菜单的html
        /// </summary>
        /// <returns></returns>
        public string LoadAccordingHtml()
        {
            var list = ModuleList();
            string sMenu = CreateAccording(list, 0);
            return sMenu;
        }

        /// <summary>
        /// 递归
        /// </summary>
        /// <param name="list"></param>
        /// <param name="Parentid"></param>
        /// <returns></returns>
        private string CreateAccording(List<ModuleEntity> list,int Parentid)
        {
            string _html = "";
            var q = list.Where(p => p.MPARENTID == Parentid && p.MDELETE == "0").OrderBy(p => p.MORDERBY);
            int i = 0;
            foreach (var t in q)
            {
                if (t.MSINGLE == 1)
                {
                    if (t.MNAME == "系统管理")
                    {
                        if (Utility.Get_UserId == 147)
                        {
                            _html += string.Format("<li class=\"mainlevel\" id=\"mainlevel_{2}\"><a href=\"{1}\" target=\"_blank\">{0}</a>", t.MNAME, t.MURL, i);
                        }
                    }
                    else
                    {
                        _html += string.Format("<li class=\"mainlevel\" id=\"mainlevel_{2}\"><a href=\"{1}\" target=\"_blank\">{0}</a>", t.MNAME, t.MURL, i);
                    }
                }
                else
                {         
                    var childlist=list.Where(p => p.MPARENTID == t.MODULEID && p.MDELETE == "0").ToList();
                    //移除没有权限菜单
                    PermissionService.RemoveNoPermission(childlist);
                    if (childlist.Count > 0)
                    {
                        _html += string.Format("<li class=\"mainlevel\" id=\"mainlevel_{1}\"><a href=\"#\">{0}</a>", t.MNAME, i);
                        _html += CreateChildAccording(list, t.MODULEID, i);
                    }
                }
                _html += "</li>";
                i++;
            }
            return _html;
        }

        /// <summary>
        /// According子菜单Html
        /// </summary>
        /// <param name="list"></param>
        /// <param name="IntParent"></param>
        /// <returns></returns>
        private string CreateChildAccording(List<ModuleEntity> list, int IntParent,int i)
        {
            string _html = "";
            var q = list.Where(p => p.MPARENTID == IntParent && p.MDELETE == "0").OrderBy(p => p.MORDERBY).ToList();
            //移除没有权限菜单
            PermissionService.RemoveNoPermission(q);
            _html += "<ul id=\"sub_" + i + "\">";
            foreach (var t in q)
            {
                
                if (t.MURL == "/Modules/Article/Index.aspx")
                {
                    _html += string.Format("<li><a href=\"" + t.MURL + "?ModuleId=" + t.MODULEID + "\">" + t.MNAME + "</a></li>");
                }
                else if (t.MURL == "/Modules/Doc/Index.aspx")
                {
                    _html += string.Format("<li><a href=\"" + t.MURL + "?ModuleId=" + t.MODULEID + "\">" + t.MNAME + "</a></li>");
                }
                else
                {
                    if (t.MTARGET == "_blank")
                    {
                        _html += string.Format("<li><a href=\"{0}\" target=\"_blank\">{1}</a></li>", t.MURL, t.MNAME, t.MTARGET);
                    }
                    else
                    {
                        _html += string.Format("<li><a href=\"{0}\">{1}</a></li>", t.MURL, t.MNAME); ;
                    }
                }
            }
            _html += "</ul>";
            return _html;
        }

        #endregion
    }
}
